package casts
{
   import flash.display.MovieClip;
   import flash.events.Event;
   import flash.utils.Dictionary;
   
   /**
    * MovieClip with reference storing in a static container.
    * @author     cjboy | cjboy1984@gmail.com
    * @usage
    * EasyMovieClip.getInstanceById('id').doSomething();
    */
   public class EasyMovieClip extends MovieClip
   {
      // must assigned this value unless you don't want to get its reference easier.
      public function get id():String { return _id || name; }
      public function set id(v:String):void
      {
         _id = v;
      }
      private var _id:String;
      
      // dictionary storing references of these.
      private static var dicts:Dictionary = new Dictionary();
      
      /* constructor */
      public function EasyMovieClip()
      {
         stop();
         
         addEventListener(Event.ADDED_TO_STAGE, onAdd);
         addEventListener(Event.REMOVED_FROM_STAGE, onRemove);
      }
      
      // --------------------- LINE ---------------------
      
      // Get the reference by the given id.
      public static function getInstanceById(v:String):Object
      {
         return dicts[v] as Object;
      }
      
      // --------------------- LINE ---------------------
      
      // ################### protected ##################
      
      protected function onAdd(e:Event = null):void
      {
         // fix the value of the id
         if (id == null || id == '')
         {
            id = name;
         }
         
         // save into dictionary
         dicts[id] = this;
      }
      
      protected function onRemove(e:Event = null):void
      {
         delete dicts[id];
      }
      
      // #################### private ###################
      
      // --------------------- LINE ---------------------
      
   }
   
}